<?php
/*
    author wangw
*/
class WxUtil
{

    /**
     * hash
     * @return [type] [description]
     */
    public static  function passwordHash($pwd)
    {
       return md5($pwd);
    }
    public static function getRandChar($length = 16){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
     }
    public static function getGoodsImgUrl($url,$width=0,$height=0)
    {
        if (empty($url)) {
            return '';
        }
        if (strpos($url, '.com') !=0 || strstr($url, '/images') !=0) {
            $url = $url;
        } else {
            if (!empty($width) && !empty($height)) {
                $url = Yii::app()->request->hostInfo.'/images/'.$url.'_w-'.$width.'_h-'.$height.'.png';
            }else if (!empty($width)) {
                $url = Yii::app()->request->hostInfo.'/images/'.$url.'_w-'.$width.'.png';
            } else if (!empty($height)) {
                $url = Yii::app()->request->hostInfo.'/images/'.$url.'_h-'.$height.'.png';
            } else {
                $url = Yii::app()->request->hostInfo.'/images/'.$url.'.png';
            }
        }
        if (!strpos($url, 'ttp://')) {
            $url = str_replace('//img','http://img',$url);
        }
        return $url;
    }
    //水印图片
    public static function getGoodsImgUrl2($url,$width=0,$height=0)
    {
        if (empty($url)) {
            return '';
        }
        if (strpos($url, '.com') !=0 || strstr($url, '/images') !=0) {
            $url = $url;
        } else {
            if (!empty($width) && !empty($height)) {
                $url = Yii::app()->request->hostInfo.'/imagecache/'.$url.'_w-'.$width.'_h-'.$height.'.png';
            } else {
                $url = Yii::app()->request->hostInfo.'/imagecache/'.$url.'.png';
            }
        }
        if (!strpos($url, 'ttp://')) {
            $url = str_replace('//img','http://img',$url);
        }
        return $url;
    }
    public static function create_uuid($prefix = ""){    //可以指定前缀
        $str = $prefix.time();
        $reg = mt_rand(100000,999999);
        $uuid = $str.$reg;
        //检查ID是否重复
        if (UuidLog::model()->isExist($uuid)) {
            return self::create_uuid();
        }
       // 增加到数据库
        UuidLog::model()->add($uuid);
        return $uuid;
    }
  
    //平安银行支付ID格式  Ymd+8位随机数 
    public static function create_uuid_for_pay($prefix = ""){    //可以指定前缀
        $str = date('Ymd');
        $reg = mt_rand(10000000,99999999);
        $uuid = $str.$reg;
        //检查ID是否重复
        if (UuidLog::model()->isExist($uuid)) {
            return self::create_uuid_for_pay($prefix);
        }
       // 增加到数据库
        UuidLog::model()->add($uuid);
        return $uuid;
    }
  
    //curl 请求
    public static function vcurl($url,$post = array(), $cookie = '', $cookiejar = '', $referer = '',$platform = ''){ 
        
         
        $tmpInfo = ''; 
        $post_data = $post;
        $beg_time =  microtime(true);
        if (!empty($post) && is_array($post)) {
            $post = http_build_query($post); 
        }
        
        // if (!empty($get) && is_array($get)) {
        //     $get = http_build_query($get);
        // }
        
        $cookiepath = getcwd().'./'.$cookiejar; 
        $curl = curl_init(); 
        curl_setopt($curl, CURLOPT_URL, $url); 
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); 

        if($referer) { 
            curl_setopt($curl, CURLOPT_REFERER, $referer); 
        } else { 
            curl_setopt($curl, CURLOPT_AUTOREFERER, 1); 
        } 
        if($post) { 
            curl_setopt($curl, CURLOPT_POST, 1); 
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post); 
        } 
        if($cookie) { 
            curl_setopt($curl, CURLOPT_COOKIE, $cookie); 
        } 
        if($cookiejar) { 
            curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiepath); 
            curl_setopt($curl, CURLOPT_COOKIEFILE, $cookiepath); 
        } 
        //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); 
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); 
        curl_setopt($curl, CURLOPT_HEADER, 0); 
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
        $tmpInfo = curl_exec($curl); 
        if (curl_errno($curl)) { 
            #echo curl_error($curl); 
            $tmpInfo = '';
        } 
        //
        $end_time = microtime(true);
        
        if (!empty($post_data)) {
        $post_data = http_build_query($post_data); 
        }
        $diff_time =$end_time - $beg_time;
        $params = array();
        $params['url'] = $url; 
        $params['use_time'] = $diff_time;
        $params['platform'] = $platform; 
        $params['data'] = $post_data;
        $params['return_status'] = curl_getinfo($curl,CURLINFO_HTTP_CODE); 
        $params['return_status_text'] = curl_error($curl);
        $params['return'] = $tmpInfo;
        file_put_contents(Yii::app()->getRuntimePath() . '/api_' . date("Y_W") . '.txt', sprintf("%s %s %s %s", date("Y-m-d H:i:s"),$params['return_status'], json_encode($params), PHP_EOL), FILE_APPEND);
        curl_close($curl); 
        
        return $tmpInfo; 
    } 

    /**
     * 电商Sign签名生成
     * @param data 内容   
     * @param appkey Appkey
     * @return DataSign签名
     */
    public static function encrypt($data, $appkey) {
        return urlencode(base64_encode(md5($data.$appkey)));
    }

    public static function Pay($order=array(),$is_app = 0,$platform = '')
    {
        /* 
        //支付方式
        const PAY_WAY_ONLINE = 1;//在线 
        const PAY_WAY_BLANCE = 2;//余额 
        */
        $result['errno'] = 0;
        $result['result'] = array();
        $extra = array();
        if (!isset($order['pay_type']) || empty($order['pay_type'])) {
            $result['errno'] = 1;//参数不正确
            $result['result'] ='支付方式必需';
            return $result;
        }
        if (empty($order) && empty($order['order_sn']) && empty($order['pay_type']) && empty($order['pay_amount'])) {
            $result['errno'] = 1;//参数不正确
            $result['result'] ='参数不正确';
            return $result;
        }
        $order['pay_amount'] = floatval(number_format($order['pay_amount'],2,'.',''));  

        $merchant_params = array();
        $merchant_params['merchant_no'] = Config::model()->get('merchant_no');//平安银行 支付账号  ----- 
        $merchant_params['merchant_cert_path'] = Config::model()->get('merchant_cert_path');//平安银行 支付证书  ----- 
        $merchant_params['merchant_cert_pass'] = Config::model()->get('merchant_cert_pass');//平安银行 支付密码  ----- 
        $merchant_params['pingan_cert_public_key'] = Config::model()->get('pingan_cert_public_key');//平安银行 支付key  ----- 
        $pay_component = new PingAn($merchant_params, YII_DEBUG);
        
        $notify_url = Yii::app()->request->hostInfo.'/order/notify/online';
        $return_url = Yii::app()->request->hostInfo.'/order/payreturn?platform=online&order_sn='.$order['order_sn'].'&pay_type='.$order['pay_type'];
          
         $params = array();
        $params['return_url'] = $return_url;
        $params['notify_url'] = $notify_url;
        $params['order_sn'] = $order['order_sn'];
        $params['amount'] = $order['pay_amount'];
        $params['product_name'] = Yii::app()->name.'费用结算';//
        $params['order_time'] = $order['ctime'];
        $result = array();
        $errors = array();
        if ($order['pay_type'] == PayInfo::PAY_WAY_ONLINE) {
            //在线支付
            $result['result'] = $pay_component->buildPayInfoWeb($params);
            $errors = $pay_component->getErrors(); 
            if (empty($errors)) {

            } else {
                $arr = array_shift($errors);
                $result['errno'] = 1114007;//支付接口报错
                $result['result'] = $arr[1];
            }
        } else {
            //余额 支付

        }
        
        $log = array();
        $log['order_info'] = $order;
        $log['params'] = $params;
        $log['result'] = $result;
        $log['errors'] = $errors; 
        file_put_contents(Yii::app()->getRuntimePath() . '/pay_request_' . date("Y_W") . '.txt', sprintf("%s %s %s", date("Y-m-d H:i:s"),  json_encode($log), PHP_EOL), FILE_APPEND);

        return $result;
    } 
    /*
    *小米推送
    *single true为单推，false 全推
    *reg_id 推送人 单推时不能为空
    *platform 推送平台
    */
    public static function messagePush($data=array())
    {
        if (empty($data)) {
            return false;
        }
        $platform_params = array();
        $platform_params['ios']['mipush_secret'] = Config::model()->get('ios_push_secret');
        $platform_params['ios']['mipush_package'] = Config::model()->get('ios_push_package');
        $platform_params['android']['mipush_secret'] = Config::model()->get('android_push_secret');
        $platform_params['android']['mipush_package'] = Config::model()->get('android_push_package');

//        if (empty($platform['ios']['mipush_secret']) || empty($platform['ios']['mipush_package'])) {
//            return false;
//        }
//        if (empty($platform['android']['mipush_secret']) || empty($platform['android']['mipush_package'])) {
//            return false;
//        }

        // 用户id, 小米是reg_id, 百度推送是push_user_id
        if ($data['single'] && empty($data['reg_id'])) {
            return false;
        }
        if (empty($data['params'])) {
            return false;
        }

        // 设置声音之类的参数
        $option = array();
        if (!empty($data['notify_id'])) {
            $option['notify_id'] = $data['notify_id'];
        }
        //
        $err = array();
        if ($data['single']) {
            //单推
            if ($data['platform'] == 'android') {
                $push_cpt = new PushComponent($platform_params['android']);
                $push_cpt->initXmPush(PushComponent::ANDROID);
                var_dump($push_cpt->pushToUser($data['params'], $data['custom'], $option, $data['reg_id']));
                // 获取错误信息
                $err  =  $push_cpt->getErrors();
            } 
            if ($data['platform'] == 'ios') {
                $push_cpt = new PushComponent($platform_params['ios']);
                $push_cpt->initXmPush(PushComponent::IOS);
                var_dump($push_cpt->pushToUser($data['params'], $data['custom'], $option, $data['reg_id']));
                // 获取错误信息
                $err  =  $push_cpt->getErrors();
            }
        } else {
            //全推
            $push_cpt = new PushComponent($platform_params['android']);
            $push_cpt->initXmPush(PushComponent::ANDROID);
            var_dump($push_cpt->pushToAll($data['params'], $data['custom'], $option));

            $push_cpt = new PushComponent($platform_params['ios']);
            $push_cpt->initXmPush(PushComponent::IOS);
            var_dump($push_cpt->pushToAll($data['params'], $data['custom'], $option));
        }
        

        if (empty($err)) {
            return true;
        } else {
            return false;
        }
        return false;
    }
    //阿里大鱼 短信发送
    public static function aliSend($sms_param = '',$rec_num='',$sms_template_code='',$extend='')
    {
        $appkey = Config::model()->get('alidayu_appkey');
        $secret = Config::model()->get('alidayu_secret');
        if (empty($appkey) || empty($secret)) {
            return -1;
        }
        if (is_array($sms_param)) {
            $sms_param = CJSON::encode($sms_param);
        }
        $c = new TopClient;
        $c->appkey = $appkey;
        $c->secretKey = $secret;
        $req = new AlibabaAliqinFcSmsNumSendRequest;
        $req->setExtend($extend);//可选 用于识别用户 类似state
        $req->setSmsType("normal");//固定 normal
        $req->setSmsFreeSignName("福天下");//签名。固定为福天下
        $req->setSmsParam($sms_param);//参数数组列表 序列化后的json字符串 与模板ID设置的参数要对应
        $req->setRecNum($rec_num);//发送到达的手机号码
        $req->setSmsTemplateCode($sms_template_code);//模板ID
        return $resp = $c->execute($req);
    }
    //阿里云通信
    public static function aliyunSend($mobile,$sms_template_code,$code,$extra=array())
    {
        
        //require_once Yii::app()->basePath."/extensions/Aliyun/vendor/autoload.php";

        // require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Config.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Profile/IClientProfile.php";

        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Profile/DefaultProfile.php";

        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/IAcsClient.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/DefaultAcsClient.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/AcsRequest.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/RpcAcsRequest.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/AcsResponse.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Auth/ISigner.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Auth/ShaHmac1Signer.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Http/HttpHelper.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Http/HttpResponse.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Exception/ClientException.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Exception/ServerException.php";
        // require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Exception/ServerException.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Api/Sms/Request/V20170525/SendSmsRequest.php";

        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Api/Sms/Request/V20170525/QuerySendDetailsRequest.php";



        // use Aliyun\Core\Auth\Credential;
        // use Aliyun\Core\Auth\ShaHmac1Signer;
        // use Aliyun\Core\Regions\ProductDomain;
        // use Aliyun\Core\Regions\Endpoint;
        // use Aliyun\Core\Regions\EndpointProvider;
        // IClientProfile

        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Auth/Credential.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Auth/ShaHmac1Signer.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Regions/ProductDomain.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Regions/Endpoint.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Regions/EndpointProvider.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/AliConfig.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Regions/EndpointConfig.php";


        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Exception/ClientException.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Exception/ServerException.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Regions/EndpointProvider.php";
        require_once Yii::app()->basePath."/extensions/Aliyun/lib/Core/Http/HttpHelper.php";
// use Aliyun\Core\Exception\ClientException;
// use Aliyun\Core\Exception\ServerException;
// use Aliyun\Core\Regions\EndpointProvider;
// use Aliyun\Core\Http\HttpHelper;

        // 加载区域结点配置
        AliConfig::load();
        $key = 'LTAIiB7KcbnD3vfM';
        $sectet = 'w49o1xZwprSk6pIdthnBFrMw7QCvre';

        //此处需要替换成自己的AK信息
        $accessKeyId = $key;//参考本文档步骤2
        $accessKeySecret = $sectet;//参考本文档步骤2
        //短信API产品名（短信产品名固定，无需修改）
        $product = "Dysmsapi";
        //短信API产品域名（接口地址固定，无需修改）
        $domain = "dysmsapi.aliyuncs.com";
        //暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）
        $region = "cn-hangzhou";
        //初始化访问的acsCleint
        $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
        DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
        $acsClient= new DefaultAcsClient($profile);
        $request = new SendSmsRequest;
        //必填-短信接收号码。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
        $request->setPhoneNumbers($mobile);
        //必填-短信签名
        $request->setSignName("好运来");
        //必填-短信模板Code
        $request->setTemplateCode($sms_template_code);
        //选填-假如模板中存在变量需要替换则为必填(JSON格式),友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        $request->setTemplateParam(CJSON::encode($code));
        //选填-发送短信流水号
        $request->setOutId($mobile.'_'.strval(time()));
        //发起访问请求
        $acsResponse = $acsClient->getAcsResponse($request);
        $acsResponse = CJSON::decode(json_encode($acsResponse));
        return $acsResponse;
    }
    //快递公司代码
    public static function expresscom()
    {
        return  array (
            
          );
    }
    //秒转换为时分秒
    public static function timeToStr($seconds = 0)
    { 
        $time = '';
        if ($seconds>86400) {
            $day = intval($seconds/86400);
            $time .= $day.'天';
            $seconds -= $day*86400;
        }
        if ($seconds > 3600){ 
            $hours = intval($seconds/3600);
            $minutes = $seconds % 3600;
            $time .= $hours."时".gmstrftime('%M#%S&', $minutes);
        }else{
            if ($seconds>=60) {
                $time .= gmstrftime('%M#%S&', $seconds);
            } else {
                $time .= gmstrftime('%S&', $seconds);
            }
        } 
        $time =  str_replace('@','时',$time);
        $time =  str_replace('#','分',$time);
        $time =  str_replace('&','秒',$time);
        return $time; 
    }
    //根据经纬度 获取 地名
    public static function getAddressByTrace($lng,$lat)
    {
        $result = '';
        $cache_key ='cache_get_name_by_trace_'.md5($lng.$lat);
        $cache_data = Yii::app()->cache->get($cache_key);
        if ($cache_data) {
            return $cache_data;
        }
        $ak = 'e6vpsV0fOciSbbRHIi1EAG9Gl74KQ0Ga';
        if (YII_DEBUG) {
            $url = 'http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location='.$lat.','.$lng.'&output=json&pois=1&ak='.$ak;
        } else {
            $url = 'https://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location='.$lat.','.$lng.'&output=json&pois=1&ak='.$ak;
        }
        $data = self::vcurl($url);
        $data = str_replace('renderReverse&&renderReverse(', '', $data);
        $data = str_replace(')', '', $data);
        $data  = (CJSON::decode($data)); 
        if (!empty($data) && $data['status'] == 0) {
            $result = $data['result']['formatted_address'];
        }
        Yii::app()->cache->set($cache_key,$result);
        return $result;
    } 
    //根据名称 获取 经纬度
    public static  function getTraceByName($city='',$address='')
    {
        $result = array();
        $result['lat'] = 0.00;
        $result['lng'] = 0.00;
        if (empty($city) || empty($address)) {
            return $result;
        }
        $city = trim($city);
        $address = trim($address);
        $cache_key ='cache_get_trace_by_name_'.md5($city.$address);
        $cache_data = Yii::app()->cache->get($cache_key);
        if ($cache_data) {
            return $cache_data;
        }
        $ak = 'e6vpsV0fOciSbbRHIi1EAG9Gl74KQ0Ga';
        $url ="http://api.map.baidu.com/geocoder/v2/?callback=renderOption&output=json&address=".$address."&city=".$city."&ak=".$ak;
        $url ="http://api.map.baidu.com/geocoder/v2/?callback=renderOption&output=json&address=".$address."&city=".$city."&ak=".$ak;
        $data = self::vcurl($url);
        $data = str_replace('renderOption&&renderOption(', '', $data);
        $data = str_replace(')', '', $data);
        $data  = (CJSON::decode($data)); 
        if (!empty($data) && $data['status'] == 0) {
            $result['lat'] = $data['result']['location']['lat'];
            $result['lng'] = $data['result']['location']['lng'];
        }
        Yii::app()->cache->set($cache_key,$result);
        return $result;
    }
    //根据 经纬度 获取距离
    public static  function getDistance($lat1=0,$lng1=0,$lat2=0,$lng2=0)
    {
        $result = array();
        $result['distance'] = 0.00;//距离 公里
        $result['duration'] = 0.00;//时间 分钟
        if (empty($lat1) || empty($lat2)) {
            return $result;
        }

        $cache_key ='cache_get_distance_'.md5($lat1.$lng1.$lat2,$lng2);
        $cache_data = Yii::app()->cache->get($cache_key);
        if ($cache_data) {
            return $cache_data;
        }
        $ak = 'e6vpsV0fOciSbbRHIi1EAG9Gl74KQ0Ga';
        $url = 'http://api.map.baidu.com/routematrix/v2/driving?output=json&origins='.$lat1.','.$lng1.'&destinations='.$lat2.','.$lng2.'&ak='.$ak;
        $data = self::vcurl($url);
        $data = (CJSON::decode($data));
        if (!empty($data) && $data['status'] == 0) {
            $result['distance'] = $data['result'][0]['distance']['text'];
            $result['duration'] = $data['result'][0]['duration']['text'];
        }
        Yii::app()->cache->set($cache_key,$result);
        return $result;
    }
    //根据地区  获取  距离
    public static function getDistanceByAddress($city1='',$address1='',$city2='',$address2='')
    {
        $address1 = WxUtil::getTraceByName($city1,$address1);
        $address2 = WxUtil::getTraceByName($city2,$address2);
        $result = WxUtil::getDistance($address1['lat'],$address1['lng'],$address2['lat'],$address2['lng']);
        return $result;
    }
    
}
?>
